package cn.kgc.shiro.web.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @author 课工场
 * @date 2024/8/22
 * @description shiro在web环境集成的配置类
 */
@Configuration
public class ShiroWebConfig {

    // 将shiro中提供的filter纳入spring容器的管理
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 配置shiro的拦截规则
        LinkedHashMap<String, String> map = new LinkedHashMap<>();

        // 放行静态资源   anon 标识匿名过滤器  不需要认证即可访问的资源
        map.put("/login.html","anon");
        map.put("/register.html","anon");
        map.put("/layui/**","anon");

        // 放行特定请求
        map.put("/user/login","anon");
        map.put("/user/register","anon");


        //  authc  是过滤器的别名
        map.put("/**","authc");

        // 添加拦截规则到ShiroFilterFactoryBean
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        // 设置没有登录的跳转路径
        shiroFilterFactoryBean.setLoginUrl("/user/unAuth");

        //  注入安全管理器到过滤器中  便于后续的认证判定操作
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        return shiroFilterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(CustomerRealm customerRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        // 给安全管理器对象 注入一个realm对象  实现认证和授权操作
        defaultWebSecurityManager.setRealm(customerRealm);
        return defaultWebSecurityManager;
    }

    @Bean
    public CustomerRealm customerRealm() {

        CustomerRealm customerRealm = new CustomerRealm();
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        md5.setHashIterations(10);
        customerRealm.setCredentialsMatcher(md5);

        return customerRealm;
    }
}
